import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken, getUserInfo, setUserInfo, removeUserInfo} from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    id:'',
    username:'',
    sex:'',
    phone:'',
    email:''
  }
}

const state =  getUserInfo()?JSON.parse(getUserInfo()):getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USERNAME: (state, username) => {
    state.username = username
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_SEX: (state, sex) => {
    state.sex = sex
  },
  SET_PHONE: (state, phone) => {
    state.phone = phone
  },
  SET_EMAIL: (state, email) => {
    state.email = email
  },
  SET_ID: (state, id) => {
    state.id = id
  },

}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password }).then(response => {
        console.log(response)
        const { result } = response
        console.log(result)
        commit('SET_TOKEN', result.token)
        commit('SET_ID', result.userinfo.id)
        setToken(result.token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state },id) {
    return new Promise((resolve, reject) => {
      getInfo(id).then(response => {
        const { result } = response
        if (!result) {
          reject('Verification failed, please Login again.')
        }
        const { username, id,name,sex,phone,email} = result
        commit('SET_USERNAME', username)
        commit('SET_NAME', name)
        commit('SET_SEX', sex)
        commit('SET_PHONE', phone)
        commit('SET_EMAIL', email)
        commit('SET_ID', id)

        setUserInfo(result)
        resolve(result)
      }).catch(error => {
        console.log(getToken())
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit }) {
    return new Promise((resolve, reject) => {
      try {
        removeToken() // must remove  token  first
        resetRouter()
        commit('RESET_STATE')
        resolve()
      }catch (e) {
        reject(e)
      }
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

